package com.leyou.item.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.api.R;
import com.baomidou.mybatisplus.extension.conditions.query.QueryChainWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.leyou.common.exception.LyException;
import com.leyou.item.dto.SpecGroupDTO;
import com.leyou.item.dto.SpecParamDTO;
import com.leyou.item.entity.SpecGroup;
import com.leyou.item.entity.SpecParam;
import com.leyou.item.mapper.SpecGroupMapper;
import com.leyou.item.service.CategoryService;
import com.leyou.item.service.SpecGroupService;
import com.leyou.item.service.SpecParamService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;

import java.util.Collection;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;
import java.util.stream.Stream;

public class SpecGroupServiceImpl extends ServiceImpl<SpecGroupMapper, SpecGroup> implements SpecGroupService {

    @Autowired
    private SpecGroupService specGroupService;
    @Autowired
    private SpecParamService specParamService;





    /**
     * 新增规格租
     * @param specGroupDTO
     */
    @Override
    public void addSpecGroup(SpecGroupDTO specGroupDTO) {
        SpecGroup specGroup = specGroupDTO.toEntity(SpecGroup.class);
        specGroupService.save(specGroup);


    }

    /**
     * 修改规格组
     * @param specGroupDTO
     */
    @Override
    public void updataSpecGroup(SpecGroupDTO specGroupDTO) {

        specGroupService.updateById(specGroupDTO.toEntity(SpecGroup.class));

    }
    /**
     * 根据商品分类id，查询规格组的集合,查询成功，返回规格组的集合
     * @param cid
     * @return
     */

    @Override
    public List<SpecGroupDTO> listSpecGroupByCategoryId(Long cid) {


        return SpecGroupDTO.convertEntityList(specGroupService.query().eq("category_id",cid).list());
    }

    @Override
    public List<SpecGroupDTO> listGroupById(Long cid) {

       //1.查询规格组信息
        List<SpecGroupDTO> groupList = SpecGroupDTO.convertEntityList(specGroupService.query().eq("category_id", cid).list());

        if (CollectionUtils.isEmpty(groupList)){
            throw new LyException(400,"该分类下的规格组不存在！");
        }
        // 查询规格参数
        List<SpecParamDTO> specParamList = specParamService.querySpecParams(cid, null, null);

        Map<Long, List<SpecParamDTO>> listMap = specParamList.stream().collect(Collectors.groupingBy(SpecParamDTO::getGroupId));
        /**
         *

        for (SpecGroupDTO groupDTO : groupList) {
            groupDTO.setParams(listMap.get(groupDTO.getId()));
        }
         */
        return groupList;


    }
}
